/*****************************************************************************
*
*  PROJECT:     Projekt-grupp6
*  FILE:        main.c
*  PURPOSE:     Main server program
*  DEVELOPER(S): Fredrik Laason <laason@kth.se>
*
*****************************************************************************/

#include "system.h"

int main(int argc, char **argv) {

   // make_demon();

    unsigned int server_socket;              
    struct sockaddr_in server_addr;            
    unsigned int client_socket;          
    struct sockaddr_in client_addr;            
    //struct in_addr client_ip_addr;       
    int addr_len;            

    unsigned int client_index;                             

    struct lobby clients[MAXPLAYERS];
    set_lobby(clients);

    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));

    listen(server_socket, BACKLOG);
    
    while(TRUE) {

        addr_len = sizeof(client_addr);
        client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &addr_len);

        if(client_socket == FALSE) {

            printf("Socket could not be created\n");
            exit(FALSE);
        } else {

            client_index = free_index(clients);

            if(client_index == -1) {

                close(client_socket);
                continue;
            }

            clients[client_index].player_id = client_index;
            printf("Klient %d skapad\n", client_index);
            clients[client_index].player_socket = client_socket;
            strcpy(clients[client_index].player_ip, inet_ntoa(client_addr.sin_addr)); 
            clients[client_index].player_port = PORT;

            pthread_create(&(clients[client_index].player_thread), NULL, client_handler, &clients);
        }
    }
    close(server_socket);
	return FALSE;
}
